package networkListener;

import org.pcap4j.core.*;
import org.pcap4j.packet.*;
import java.util.Date;

import org.pcap4j.core.*;
import org.pcap4j.packet.*;
import org.pcap4j.packet.namednumber.EtherType;

import java.util.Date;

public class NetworkListener {

    private PcapHandle handle;
    private CsvLogger csvLogger = new CsvLogger();
    private PacketStatistics packetStatistics = new PacketStatistics();

    public NetworkListener(PcapNetworkInterface device) throws PcapNativeException {
        this.handle = device.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 1000);
    }

    public void startListening() {
        PacketListener listener = packet -> {
            PacketProcessor processor = new PacketProcessor(packet);
            String[] packetData = processor.processPacket();
            if (packetData != null) {
                String timestamp = new Date().toString();
                csvLogger.logToCsv(timestamp, packetData);
                packetStatistics.addStatistics(packetData[0] + " -> " + packetData[2], Long.parseLong(packetData[4]));
                packetStatistics.addStatistics(packetData[1] + " -> " + packetData[3], Long.parseLong(packetData[4]));
                System.out.println("Captured packet: " + packetData[0] + " -> " + packetData[2] + ", Length: " + packetData[4] + " bytes");
            }
        };

        try {
            handle.loop(-1, listener);
        } catch (PcapNativeException | NotOpenException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void stopListening() {
        if (handle != null && handle.isOpen()) {
            handle.close();
        }
    }

    public void printStats() {
        packetStatistics.printStatistics();
    }
}